/* eslint-disable no-undef */
import router from '@/router'
import { useUserStore } from '@/stores'
import axios from 'axios'


//jsfhsgfuaguydwguw
const baseURL = 'http://115.190.94.156:8010'

//dshduiashduawyyyyey
const instance = axios.create({
  baseURL,
  timeout: 100000
})

//shdusadguasyteybchs
instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    config.headers.Authorization = userStore.token
    return config
  },
  (err) => {
    ElMessage({ message: '服务异常', type: 'error' })
    return Promise.reject(err)
  }
)

//dashdiahdwdhbcsjas
instance.interceptors.response.use(
  (res) => {
    if (res.data.code != 200) {
      if(res.data.code === 40402 || res.data.code === 40404 || res.data.code === 40401 || res.data.code === 40405){

        const userStore = useUserStore()
        const refreshToken = userStore.rtoken

        return axios.get(baseURL + '/user/refresh', {
          headers: {
            "Refresh-Token": refreshToken,
          }
        }).then(r => {
          if (r.data.code === 200){
            const token = r.headers.get('authorization')
            userStore.setToken(token)
            const rtoken = r.headers.get('refresh-token')
            userStore.setRtoken(rtoken)
            res.config.headers.Authorization = token
            return axios(res.config)
          }else{
            userStore.setToken(undefined)
            userStore.setRtoken(undefined)
            router.push('/login')
            return Promise.reject(r)
          }
        }).catch(err => {
          userStore.setToken(undefined)
          userStore.setRtoken(undefined)
          router.push('/login')
          return Promise.reject(err);
        })
      }
      ElMessage({ message: res.data.message || '服务异常', type: 'error' })
      return Promise.reject(res)
    }

    const token = res.headers.get('authorization')
    const rtoken = res.headers.get('refresh-token')
    if (token) {
      const userStore = useUserStore()
      userStore.setToken(token)
    }
    if (rtoken) {
      const userStore = useUserStore()
      userStore.setRtoken(rtoken)
    }
    return res
  },
  (err) => {
    ElMessage({ message: '服务异常', type: 'error' })
    return Promise.reject(err)
  }
)

export default instance
export { baseURL }
